image: docker

stages:
  - build
  - deploy

variables:
  IMAGE_NAME: $CI_REGISTRY_IMAGE

build-job:
  services:
    - "docker:dind"
  stage: build
  before_script:
    - docker login -u $CI_DEPLOY_USER -p $CI_DEPLOY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $IMAGE_NAME:latest || true
    - docker build --cache-from $IMAGE_NAME:latest  --build-arg BUILDKIT_INLINE_CACHE=1 --tag $IMAGE_NAME:$CI_COMMIT_SHORT_SHA --tag $IMAGE_NAME:latest .
    - docker push $IMAGE_NAME:$CI_COMMIT_SHORT_SHA
    - docker push $IMAGE_NAME:latest
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy:
  stage: deploy
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client git -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $REMOTE_HOST >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - ssh $REMOTE_USER@$REMOTE_HOST docker login -u $CI_DEPLOY_USER -p $CI_DEPLOY_PASSWORD $CI_REGISTRY
  script:
    - cd $CI_PROJECT_DIR
    - ssh $REMOTE_USER@$REMOTE_HOST docker pull $IMAGE_NAME:$CI_COMMIT_SHORT_SHA
    - DOCKER_HOST="ssh://$REMOTE_USER@$REMOTE_HOST" docker-compose up -d
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
